const Alarm = require('../models/Alarm.js');
const ModelTask = require('../models/ModelTask.js');

// Get all alarms (paginated)
const getAlarms = async (ctx) => {
  try {
    const page = parseInt(ctx.query.page) || 1;
    const pageSize = parseInt(ctx.query.pageSize) || 10;
    const offset = (page - 1) * pageSize;

    const { count, rows } = await Alarm.findAndCountAll({
      offset: offset,
      limit: pageSize,
      include: [
        { model: ModelTask, attributes: ['name', 'description'] }
      ]
    });

    ctx.body = {
      code: 200,
      data: {
        total: count,
        records: rows,
      },
      message: 'Success',
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = { code: 500, message: error.message };
  }
};

// Get alarm by ID
const getAlarmById = async (ctx) => {
  try {
    const alarm = await Alarm.findByPk(ctx.params.id, {
        include: [
            { model: ModelTask }
        ]
    });
    if (alarm) {
      ctx.body = {
        code: 200,
        data: alarm,
        message: 'Success',
      };
    } else {
      ctx.status = 404;
      ctx.body = { code: 404, message: 'Alarm not found' };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { code: 500, message: error.message };
  }
};

// Create new alarm
const createAlarm = async (ctx) => {
  try {
    const alarm = await Alarm.create(ctx.request.body);
    ctx.status = 200;
    ctx.body = {
      code: 200,
      data: alarm,
      message: 'Alarm created successfully',
    };
  } catch (error) {
    ctx.status = 400;
    ctx.body = { code: 400, message: error.message };
  }
};

// Update alarm
const updateAlarm = async (ctx) => {
  try {
    const [updated] = await Alarm.update(ctx.request.body, {
      where: { id: ctx.params.id },
    });
    if (updated) {
      const updatedAlarm = await Alarm.findByPk(ctx.params.id);
      ctx.body = {
        code: 200,
        data: updatedAlarm,
        message: 'Alarm updated successfully',
      };
    } else {
      ctx.status = 404;
      ctx.body = { code: 404, message: 'Alarm not found' };
    }
  } catch (error) {
    ctx.status = 400;
    ctx.body = { code: 400, message: error.message };
  }
};

// Delete alarm
const deleteAlarm = async (ctx) => {
  try {
    const deleted = await Alarm.destroy({
      where: { id: ctx.params.id },
    });
    if (deleted) {
        ctx.body = {
        code: 200,
        message: 'Alarm deleted successfully',
      };
    } else {
      ctx.status = 404;
      ctx.body = { code: 404, message: 'Alarm not found' };
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { code: 500, message: error.message };
  }
};

module.exports = {
  getAlarms,
  getAlarmById,
  createAlarm,
  updateAlarm,
  deleteAlarm
};